package com.leetcode.string;

import java.util.HashMap;
import java.util.Map;

public class FirstUniqCharTest {
    public static void main(String[] args) {
        String s = "123456";
        int i = firstUniqChar2(s);
        System.out.println(i);
    }

    private static int firstUniqChar(String s) {
        HashMap<Character, Integer> hm = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            hm.put(c, hm.getOrDefault(c, 0) + 1);
        }

        for (int i = 0; i < s.length(); i++) {
            if (hm.get(s.charAt(i)) == 1){
                return i;
            }
        }
        return -1;
    }

    private static int firstUniqChar2(String s) {
        HashMap<Character, Integer> hm = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (hm.containsKey(c)){
                hm.put(c,-1);
            }else {
                hm.put(c,i);
            }
        }

        int n = s.length();
        for (Map.Entry<Character, Integer> entry : hm.entrySet()) {
            Integer value = entry.getValue();
            if (value != -1 && value < n){
                n = value;
            }
        }
        if (n == s.length()){
            return -1;
        }else {
            return n;
        }

    }
}
